<template>
  <div class="Reg">
    <div class="container">
      <div class="login-wrapper">
        <div class="login-header">SilverSky</div>
        <div class="form-wrapper">
          <el-form :model="regForm">
            <el-form-item>
              <input type="text" name="username" placeholder="用户名" class="input-item" v-model="regForm.username">
            </el-form-item>
            <el-form-item>
              <input type="password" name="password" placeholder="密码" class="input-item" v-model="regForm.password">
            </el-form-item>
            <el-form-item>
              <input type="text" name="phone" placeholder="手机" class="input-item" v-model="regForm.phone">
            </el-form-item>
            <el-form-item>
              <input type="text" name="email" placeholder="邮箱" class="input-item" v-model="regForm.email">
            </el-form-item>
          </el-form>
          <div class="btn" @click="reg()">注册</div>
        </div>
      </div>
    </div>
  </div>
</template>

<style>
@import '../../public/css/login.css';

.Reg {
  background: url("~../../public/background.png") no-repeat center;
  background-size: 100%;
  position: absolute;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
}
</style>

<script>
import axios from "axios";

export default {
  data() {
    return {
      regForm: {
        username: '',
        password: '',
        phone: '',
        email: ''
      }
    }
  },
  methods: {
    reg() {
      let url = "http://localhost:8080/admins/reg";
      let data = {
        'username': this.regForm.username,
        'password': this.regForm.password,
        'phone': this.regForm.phone,
        'email': this.regForm.email
      }
      let regEmail = /^[A-Za-z\d]+([-_.][A-Za-z\d]+)*@([A-Za-z\d]+[-.])+[A-Za-z\d]{2,5}$/;
      if (this.regForm.username.trim().length < 2) {
        this.$message.error({
          message: "用户名不能少于2字!"
        })
      } else if (this.regForm.password.length < 6) {
        this.$message.error({
          message: "密码不能少于6位!"
        })
      } else if (this.regForm.phone.length !== 11 && !Number.isInteger(this.regForm.phone)) {
        this.$message.error({
          message: "手机号格式不正确!"
        })
      } else if (!regEmail.test(this.regForm.email)) {
        this.$message.error({
          message: "Email格式不正确!"
        })
      } else {
        console.log(data)
        axios.post(url, data).then((response) => {
          console.log(response);
          if (response.data.state === 2000) {
            this.$message({
              message: '用户注册成功!',
              type: 'success'
            })
            location.href ="/"
          } else {
            this.$message.error({
              message: response.data.message
            })
          }
        })
      }
    }
  }
}
</script>